from flask import request, jsonify
from app.extensions import db
from app.models import Node, NodeSchema
from app.utils.auth import require_auth, verify_chart_ownership
from . import api_bp

node_schema = NodeSchema()
nodes_schema = NodeSchema(many=True)

@api_bp.route('/nodes', methods=['GET'])
@require_auth
def get_nodes(current_user):
    try:
        chart_id = request.args.get('chart_id')
        if chart_id:
            # 验证用户是否拥有该图表
            if not verify_chart_ownership(current_user, chart_id):
                return jsonify({
                    'code': 403,
                    'message': 'Access denied',
                    'data': None
                }), 403
            nodes = Node.query.filter_by(chart_id=chart_id, status='active').all()
        else:
            # 如果没有指定chart_id，返回错误（必须指定图表）
            return jsonify({
                'code': 400,
                'message': 'chart_id is required',
                'data': None
            }), 400

        result = nodes_schema.dump(nodes)
        return jsonify({
            'code': 200,
            'message': 'success',
            'data': result
        })
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': str(e),
            'data': None
        }), 500

@api_bp.route('/nodes/<int:node_id>', methods=['GET'])
def get_node(node_id):
    try:
        node = Node.query.get(node_id)
        if not node:
            return jsonify({
                'code': 404,
                'message': 'Node not found',
                'data': None
            }), 404

        result = node_schema.dump(node)
        return jsonify({
            'code': 200,
            'message': 'success',
            'data': result
        })
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': str(e),
            'data': None
        }), 500

@api_bp.route('/nodes', methods=['POST'])
def create_node():
    try:
        data = request.get_json()
        node = Node(**data)
        db.session.add(node)
        db.session.commit()

        result = node_schema.dump(node)
        return jsonify({
            'code': 201,
            'message': 'Node created successfully',
            'data': result
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'message': str(e),
            'data': None
        }), 500

@api_bp.route('/nodes/<int:node_id>', methods=['PUT'])
def update_node(node_id):
    try:
        node = Node.query.get(node_id)
        if not node:
            return jsonify({
                'code': 404,
                'message': 'Node not found',
                'data': None
            }), 404

        data = request.get_json()
        for key, value in data.items():
            if hasattr(node, key):
                setattr(node, key, value)

        db.session.commit()
        result = node_schema.dump(node)
        return jsonify({
            'code': 200,
            'message': 'Node updated successfully',
            'data': result
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'message': str(e),
            'data': None
        }), 500

@api_bp.route('/nodes/<int:node_id>', methods=['DELETE'])
def delete_node(node_id):
    try:
        node = Node.query.get(node_id)
        if not node:
            return jsonify({
                'code': 404,
                'message': 'Node not found',
                'data': None
            }), 404

        db.session.delete(node)
        db.session.commit()
        return jsonify({
            'code': 200,
            'message': 'Node deleted successfully',
            'data': None
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'message': str(e),
            'data': None
        }), 500